﻿using System;
using System.Collections.Generic;
using System.Web;
using Domino;
using System.Runtime.InteropServices;

namespace NotesCommonProjects
{
    /// <summary>NOTES_004：檢查高雄廠承攬商是否有申請進入工廠API(KNOTES01/K/CCP, knewProject.nsf)</summary>
    /// ConstructionDate = 進入製程區作業日期。請依日期格式【YYYY/MM/DD】傳入，例如【2014/02/14】。
    /// ContractorsID = 承攬商的指型辨別編號。請依Notes AP中承攬商人員基本資料的格式傳入，例如【*002001】。

    public class CheckFactoryEntryApply : IHttpHandler
    {
        //宣告Notes物件
        public NotesSession Session;
        public NotesDatabase Db;
        //public NotesForm Form;
        public NotesView View;
        public NotesDocumentCollection TempDocs;
        public NotesDocument CurrentDoc;

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";

            try
            {
                //【01】建立NotesSession
                Session = new NotesSession();

                //Initialize方法會自動抓目前系統登入使用的Notes id檔, 並要求輸入密碼
                //Session.Initialize(NotesCF.MyIdPassword);
                Session.Initialize(NotesCF.AutoCCPTIdPassword); //AutoCCPT

                //【02】檢查POST來的參數
                if (String.IsNullOrEmpty(req.Form["ConstructionDate"]) || String.IsNullOrEmpty(req.Form["ContractorsID"]))
                    throw new Exception(NotesCF.ExceptionMessage_01);

                //【03】取得POST參數
                string ConstructionDate = Convert.ToString(req.Form["ConstructionDate"]);
                string ConstractorsID = Convert.ToString(req.Form["ContractorsID"]);

                //【04】做Notes文件
                //取得指定的NotesDatabase
                Db = Session.GetDatabase(NotesCF.KNotes01, "knewProject.nsf", false);

                //取得指定的NotesForm
                //Form = Db.GetForm(DummyObject.Form);

                //取得指定的NotesView
                View = Db.GetView("vRobot");

                //檢查此文件是否已存在
                TempDocs = View.GetAllDocumentsByKey(ConstructionDate);
                ReturnObject ReturnObject = new ReturnObject(false);    //CanPass = false

                if (TempDocs != null)    //文件存在
                {
                    //檢查多重值欄位SC_ID是否包含ContractorsID
                    CurrentDoc = TempDocs.GetFirstDocument();
                    for (int i = 1; i <= TempDocs.Count; i++)
                    {
                        bool CanPass = CheckContractorsID(CurrentDoc, ConstractorsID);
                        if (CanPass)
                        {
                            ReturnObject.CanPass = true;
                            break;  //不繼續檢查TempDocs了
                        }
                        else
                        {
                            NotesDocument TempDoc = CurrentDoc;
                            CurrentDoc = TempDocs.GetNextDocument(TempDoc);

                            //釋放COM NotesDocument元件
                            Marshal.FinalReleaseComObject(TempDoc);
                            TempDoc = null;
                        }
                    }
                    //Go Next Document
                }

                //【05】回傳結果
                resp.ContentType = "application/json";
                resp.Charset = null;
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = fastJSON.JSON.Instance.ToJSON(ReturnObject);

                //【06】寫入Log
                string LogContext = "【ConstructionDate】 【" + Convert.ToString(req.Form["ConstructionDate"]) + "】"
                     + "【ContractorsID】 【" + Convert.ToString(req.Form["ContractorsID"]) + "】"
                     + "【回傳結果】 【" + resultStr + "】";
                NotesCF.WriteLog(NotesCF.CheckFactoryEntryApplyLogDir, LogContext);
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = NotesCF.Ex2Xml(ex, false);

                //寫入Log
                string LogContext = "【呼叫失敗】 【" + ex.Message + "】";
                NotesCF.WriteLog(NotesCF.CheckFactoryEntryApplyLogDir, LogContext);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();

                //釋放COM物件, 要反過來釋放
                Marshal.FinalReleaseComObject(CurrentDoc);
                CurrentDoc = null;
                Marshal.FinalReleaseComObject(TempDocs);
                TempDocs = null;
                Marshal.FinalReleaseComObject(View);
                View = null;
                Marshal.FinalReleaseComObject(Db);
                Db = null;
                Marshal.FinalReleaseComObject(Session);
                Session = null;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public bool CheckContractorsID(NotesDocument Doc, string ConstractorsID)
        {
            //取得SC_ID欄位值(ex:*010020, *010021, *010022)
            object[] SC_ID = Doc.GetItemValue("SC_ID");

            //將SC_ID分成陣列
            List<string> SC_IDs = new List<string>();
            foreach (object o in SC_ID)
            {
                SC_IDs.Add(Convert.ToString(o).Trim());
            }

            //ConstractorsID : 輸入的ID
            //SC_IDs : 文件中的IDs
            //進行比對
            if (SC_IDs.Contains(ConstractorsID))
                return true;
            else
                return false;
        }
    }

    public class ReturnObject
    {
        public bool CanPass { get; set; }

        public ReturnObject(bool can_pass)
        {
            CanPass = can_pass;
        }

        public ReturnObject() { }
    }
}
